//
// Created by cy on 22-5-16.
//
#include "except.hpp"

using namespace std;
using namespace fmt;

CecException::CecException(const string &error) {
    auto &&str = format(
    "\033[31;22m\n{}CecException: {}\033[0m", Teuchos::get_stacktrace(1), error
    );
    m_error = new char[strlen(str.c_str())];
    strcpy(m_error, str.c_str());
    signal(SIGABRT, SIG_DFL);
    cout << str << endl;
}

CecException::CecException(const exception &except) {
    auto &&str = format(
            "\033[31;22m\n{}{}\033[0m", Teuchos::get_stacktrace(1), except.what()
    );
    m_error = new char[strlen(str.c_str())];
    strcpy(m_error, str.c_str());
    signal(SIGABRT, SIG_DFL);
    cout << str << endl;
}

CecException::~CecException() noexcept {
    delete m_error;
}

char const *CecException::what() const noexcept {
    return m_error;
}

void CecException::printStackTrace() {
    cout << m_error << endl;
}

int CecException::registerException() noexcept{
    signal(SIGSEGV, segvCallBackHandel);
    signal(SIGABRT, abrtCallBackHandel);
    return 0;
}

void CecException::abrtCallBackHandel(int sig_num) {
    auto &&str = format(
            "\033[31;22m\n{}CecException: {}\033[0m", Teuchos::get_stacktrace(), "被外部程序强制终止!"
    );
    cout << str << endl;
}

void CecException::segvCallBackHandel(int sig_num) {
    signal(SIGABRT, SIG_DFL);
    auto &&str = format(
            "\033[31;22m\n{}CecException: {}\033[0m", Teuchos::get_stacktrace(), "非法内存访问，分段错误!"
    );
    cout << str << endl;
    abort();
}